package first.codeTop.byteDance;

/**
 * @ClassName Leetcode33
 * @description:
 * @author: 荣燊
 * @create: 2021-07-27 10:46
 **/
public class Leetcode33 {
    //  搜索旋转排序数组

    public static void main(String[] args) {
        int[] nums = {3,-1};
        int target = 3;
        System.out.println(search(nums, target));
    }

    // 二分法，使用二分法将数组分成两部分，至少有一部分是有序的
    public static int search(int[] nums, int target) {
        int l = 0;
        int r = nums.length-1;
        if (nums.length == 0) {
            return -1;
        }
        if (nums.length == 1) {
            return nums[0] == target ? 0 : -1;
        }
        while (l <= r) {
            int mid = (l+r) / 2;
            if (nums[mid] == target) {
                return mid;
            }
            // 这里用nums[0] 直接判断前半段是否有序
            // 为什么使用<= ：测试用例{3,1}，target=1,只有两个数，mid==0
            if (nums[0] <= nums[mid]) {
                if (nums[0] <= target && nums[mid] > target) {
                    r = mid - 1;
                } else {
                    l = mid + 1;
                }
            } else {
                if (nums[mid] < target && nums[r] >= target) {
                    l = mid + 1;
                } else {
                    r = mid - 1;
                }
            }
        }
        return -1;
    }

    public static int find(int[] nums, int i, int j, int target) {
        int tmp = (i+j) / 2;
        if (nums[tmp] == target) {
            return tmp;
        }
        while (i < j) {
            if (nums[i] < nums[tmp-1] && target > nums[i] || target < nums[tmp-1]) {
                return find(nums, i, tmp-1, target);
            } else {
                return find(nums, tmp+1, j, target);
            }
        }
        return -1;
    }
}
